package com.jc.camerascan.activity.camera;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.google.android.cameraview.CameraView;
import com.jc.camerascan.R;
import com.jc.camerascan.activity.ScanResultActivity;
import com.jc.camerascan.utils.RotateSensorHelper;
import com.jc.camerascan.utils.Utils;
import com.jc.camerascan.utils.XToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.annotation.Permission;
import com.xuexiang.xrouter.utils.TextUtils;
import com.xuexiang.xui.widget.alpha.XUIAlphaImageView;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.jc.camerascan.activity.camera.PictureCropActivity.KEY_PICTURE_PATH;
import static com.jc.camerascan.activity.camera.PictureCropActivity.REQUEST_CODE_PICTURE_CROP;
import static com.xuexiang.xaop.consts.PermissionConsts.CAMERA;
import static com.xuexiang.xaop.consts.PermissionConsts.STORAGE;

/**
 * @ProjectName: PhotoRecognition
 * @Package: com.jc.camerascan.activity.camera
 * @ClassName: CameraActivity
 * @Description: 拍照界面
 * @Author: XuChi
 * @CreateDate: 2020/7/15 9:55
 * @Version: 1.0
 */
public class CameraActivity extends AppCompatActivity {
    public static final int REQUEST_CODE_OPEN_CAMERA = 1245;

    private static final int[] FLASH_OPTIONS = {
            CameraView.FLASH_AUTO,
            CameraView.FLASH_OFF,
            CameraView.FLASH_ON,
    };

    private static final int[] FLASH_ICONS = {
            R.drawable.ic_flash_auto,
            R.drawable.ic_flash_off,
            R.drawable.ic_flash_on,
    };
    private int mCurrentFlash;


    @BindView(R.id.iv_flash_light)
    XUIAlphaImageView ivFlashLight;
    @BindView(R.id.iv_camera_close)
    XUIAlphaImageView ivCameraClose;
    @BindView(R.id.iv_take_photo)
    XUIAlphaImageView ivTakePhoto;
    @BindView(R.id.iv_picture_select)
    XUIAlphaImageView ivPictureSelect;
    @BindView(R.id.camera_view)
    CameraView mCameraView;

    private Unbinder mUnbinder;

    private RotateSensorHelper mSensorHelper;

    private boolean noResultFinish = false;

    private String scanType = "";

    private int idCardType = 0;

    @Permission({CAMERA, STORAGE})
    public static void open(@NonNull Context context, String scanType) {
        Intent intent = new Intent(context, CameraActivity.class);
        intent.putExtra("scanType", scanType);
        context.startActivity(intent);
    }

    @Permission({CAMERA, STORAGE})
    public static void open(@NonNull Activity activity) {
        activity.startActivityForResult(new Intent(activity, CameraActivity.class), REQUEST_CODE_OPEN_CAMERA);
    }

    @Permission({CAMERA, STORAGE})
    public static void open(@NonNull Activity activity, int requestCode) {
        activity.startActivityForResult(new Intent(activity, CameraActivity.class), requestCode);
    }

    @Permission({CAMERA, STORAGE})
    public static void open(@NonNull Fragment fragment) {
        fragment.startActivityForResult(new Intent(fragment.getContext(), CameraActivity.class), REQUEST_CODE_OPEN_CAMERA);
    }

    @Permission({CAMERA, STORAGE})
    public static void open(@NonNull Fragment fragment, int requestCode) {
        fragment.startActivityForResult(new Intent(fragment.getContext(), CameraActivity.class), requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        mUnbinder = ButterKnife.bind(this);

        if (mCameraView != null) {
            mCameraView.addCallback(mCallback);
        }

        scanType = getIntent().getStringExtra("scanType");
        if (scanType != null && !scanType.isEmpty()) {
            noResultFinish = false;
        } else {
            noResultFinish = true;
        }

        List<View> views = new ArrayList<>();
        views.add(ivFlashLight);
        views.add(ivCameraClose);
        views.add(ivTakePhoto);
        views.add(ivPictureSelect);
        mSensorHelper = new RotateSensorHelper(this, views);

        if (scanType.contains("SFZSB")) {
            new MaterialDialog.Builder(this)
                    .title("请选择身份证的相反面")
                    .items(R.array.idcard_side)
                    .cancelable(false)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                            idCardType = position;
                        }
                    })
                    .show();
        }
    }

    @OnClick({R.id.iv_camera_close, R.id.iv_flash_light, R.id.iv_take_photo, R.id.iv_picture_select})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_camera_close:
                finish();
                break;
            case R.id.iv_flash_light:
                if (mCameraView != null) {
                    mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length;
                    ivFlashLight.setImageResource(FLASH_ICONS[mCurrentFlash]);
                    mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]);
                }
                break;
            case R.id.iv_take_photo:
                if (mCameraView != null) {
                    mCameraView.takePicture();
                }
                break;
            case R.id.iv_picture_select:
                Utils.getPictureSelector(this)
                        .maxSelectNum(1)
                        .isCamera(false)
                        .compress(true)
                        .enableCrop(false)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            default:
                break;
        }
    }

    /**
     * 拍照的回调
     */
    private CameraView.Callback mCallback = new CameraView.Callback() {
        @Override
        public void onCameraOpened(CameraView cameraView) {
        }

        @Override
        public void onCameraClosed(CameraView cameraView) {
        }

        @Override
        public void onPictureTaken(final CameraView cameraView, final byte[] data) {
            handlePictureTaken(data);
        }
    };

    @IOThread
    private void handlePictureTaken(byte[] data) {
        String picPath = Utils.handleOnPictureTaken(data);
        if (!StringUtils.isEmpty(picPath)) {
            PictureCropActivity.open(this, true, picPath);
//            goToResult(picPath);
        } else {
            XToastUtils.error("图片保存失败！");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    List<LocalMedia> result = PictureSelector.obtainMultipleResult(data);
                    if (result.get(0).getCompressPath() != null) {
                        goToResult(result.get(0).getCompressPath());
//                        PictureCropActivity.open(this, false, result.get(0).getCompressPath());
                    } else {
//                        PictureCropActivity.open(this, false, result.get(0).getRealPath());
                        goToResult(result.get(0).getRealPath());
                    }
//                    PictureCropActivity.open(this, false, result.get(0).getPath());
                    break;
                case REQUEST_CODE_PICTURE_CROP:
                    if (noResultFinish) {
                        setResult(RESULT_OK, data);
                        finish();
                    } else {
                        String imgPath = data.getStringExtra(KEY_PICTURE_PATH);
//                        ImageLoader.get().loadImage(ivContent, imgPath);
//                        goToResult(imgPath);
                        if (scanType.contains("SFZSB")) {
                            ScanResultActivity.start(CameraActivity.this, imgPath, scanType, idCardType);
                        } else {
                            ScanResultActivity.start(CameraActivity.this, imgPath, scanType);
                        }
                        finish();
                        finish();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void goToResult(String picPath) {
        Luban.with(this)
                .load(picPath)
                .ignoreBy(100)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
//                            handlePictureResult(file.getPath());
                        if (scanType.contains("SFZSB")) {
                            ScanResultActivity.start(CameraActivity.this, file.getAbsolutePath(), scanType, idCardType);
                        } else {
                            ScanResultActivity.start(CameraActivity.this, file.getAbsolutePath(), scanType);
                        }
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCameraView != null) {
            mCameraView.start();
        }
    }

    @Override
    protected void onPause() {
        if (mCameraView != null) {
            mCameraView.stop();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        if (isFinishing()) {
            onRelease();
        }
        super.onStop();
    }

    /**
     * 资源释放
     */
    protected void onRelease() {
        mSensorHelper.recycle();
    }
}
